package co.fitstart.mobile.web.controller.experience;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.demo2do.core.support.Result;
import com.demo2do.core.utils.JsonUtils;
import com.demo2do.core.wechat.web.interceptor.WechatJsConfig;

import co.fitstart.entity.coupon.Coupon;
import co.fitstart.entity.coupon.CouponBatch;
import co.fitstart.entity.course.round.CourseRound;
import co.fitstart.entity.order.Order;
import co.fitstart.entity.user.User;
import co.fitstart.mobile.handler.ActivateHandler;
import co.fitstart.mobile.service.CouponService;
import co.fitstart.mobile.service.CourseRoundService;
import co.fitstart.mobile.service.OrderService;
import co.fitstart.mobile.web.interceptor.MobileDetect;
import co.fitstart.mobile.web.interceptor.Router;
import co.fitstart.mobile.web.interceptor.WechatAuthority;
import co.fitstart.mobile.web.resolver.Secure;

/**
 * 
 * @author lidan
 *
 */
@Controller
@RequestMapping("/experience-coupons/{couponBatchId}")
public class ExperienceCouponController {
    
    private static final Logger logger = LoggerFactory.getLogger(ExperienceCouponController.class);
    
    @Autowired
    private CouponService couponService;
    
    @Autowired
    private OrderService orderService;
    
    @Autowired
    private CourseRoundService courseRoundService;
    
    @Autowired
    private ActivateHandler activateHandler;
    
    /**
     * 
     * @param couponBathId
     * @return
     */
    @RequestMapping(value = "/identify", method = RequestMethod.GET)
    public ModelAndView identifyCoupon(@PathVariable("couponBatchId") Long couponBathId) {
        ModelAndView modelAndView = new ModelAndView("experience/coupon-identify");
        
        CouponBatch couponBatch = couponService.loadCouponBatch(couponBathId);
        modelAndView.addObject("couponBatch", couponBatch);
        
        return modelAndView;
    }
    
    /**
     * 
     * @param couponBatchId
     * @param mobile
     * @param contactPerson
     * @param wechatNumber
     * @return
     */
    @RequestMapping(value = "/identify", method = RequestMethod.PATCH)
    public @ResponseBody String onIdentifyCoupon(@PathVariable("couponBatchId") Long couponBatchId,
                                                 @RequestParam("mobile") String mobile,
                                                 @RequestParam("contactPerson") String contactPerson,
                                                 @RequestParam("wechatNumber") String wechatNumber) {
        Result result = new Result();
        
        try {
            
            CouponBatch couponBatch = couponService.loadCouponBatch(couponBatchId);
            
            Coupon coupon = couponService.loadCoupon(mobile, couponBatch);
            if (coupon != null) {
                
                if (coupon.getStatus().isUsed()) {
                    result.success().message("您已激活，请去个人中心查看");
                } else {
                    result.success().data("code", coupon.getCode()).message("您已认领过该优惠券，请不要重复认领");
                }
            } else {
                
                Coupon thisCoupon = couponService.createCoupon(couponBatch, mobile, contactPerson, wechatNumber);
                
                result.success().data("code", thisCoupon.getCode()).message("认领优惠券成功");
            }
            
        } catch (Exception e) {
            
            logger.error("onIdentifyCoupon() error", e);
            result.fail().message("认领优惠券失败");
            
        }
        return JsonUtils.toJsonString(result);
    }
    
    /**
     * 
     * @param couponBathId
     * @return
     */
    @RequestMapping(value = "/identified", method = RequestMethod.GET)
    public ModelAndView identifiedCoupon(@PathVariable("couponBatchId") Long couponBathId) {
        ModelAndView modelAndView = new ModelAndView("experience/coupon-identified");
        
        CouponBatch couponBatch = couponService.loadCouponBatch(couponBathId);
        
        modelAndView.addObject("couponBatch", couponBatch);
        
        return modelAndView;
    }
    
    /**
     * 
     * @param couponBathId
     * @return
     */
    @RequestMapping(value = "/activate", method = RequestMethod.GET)
    @Router(targetUrl = "/required-wechat")
    @WechatAuthority
    @MobileDetect
    @WechatJsConfig
    public ModelAndView activateCoupon(@PathVariable("couponBatchId") Long couponBathId, @RequestParam("site") Long siteId) {
        ModelAndView modelAndView = new ModelAndView("experience/coupon-activate");
        
        CouponBatch couponBatch = couponService.loadCouponBatch(couponBathId);
        
        modelAndView.addObject("couponBatch", couponBatch);
        modelAndView.addObject("site", siteId);
        
        return modelAndView;
    }
    
    /**
     * 
     * @param couponBatchId
     * @return
     */
    @RequestMapping(value = "/activate", method = RequestMethod.PATCH)
    @Router(targetUrl = "/required-wechat")
    @WechatAuthority
    @MobileDetect
    @WechatJsConfig
    public @ResponseBody String onActivateCoupon(@Secure User user,
                                                 @PathVariable("couponBatchId") Long couponBatchId,
                                                 @RequestParam("code") String code,
                                                 @RequestParam("mobile") String mobile,
                                                 @RequestParam("site") Long siteId) {
        Result result = new Result();
        
        try {
            String url = "/experience-coupons/" + couponBatchId + "/activated";
            CouponBatch couponBatch = couponService.loadCouponBatch(couponBatchId);
            
            Coupon coupon = couponService.loadCoupon(user.getId(), couponBatch);
            if (coupon == null) {
                String identifyUrl = "/experience-coupons/" + couponBatchId + "/identify";
                result.fail().data("url", identifyUrl).message("您未领取该优惠券");
            } else if (coupon != null && (!coupon.getCode().equalsIgnoreCase(code) || !coupon.getIdentification().equalsIgnoreCase(mobile))) {
                result.fail().message("请输入正确的券码或手机号");
            }
            else if(coupon != null && coupon.getCode().equalsIgnoreCase(code) && coupon.getIdentification().equalsIgnoreCase(mobile)){
                if(coupon.getStatus().isUsed()) {
                    result.success().data("url", url).message("您已激活");
                } else {
                    Result payResult = activateHandler.activateCoupon(coupon, user, siteId);
                    if (!payResult.isValid()) {
                        result.fail().message("支付失败");
                    } else {
                        result.success().data("url", url).message("激活成功");
                    }
                }
                
            }
            
        } catch (Exception e) {
            logger.error("onActivateCoupon() error", e);
            result.fail().message("激活失败");
            
        }
        return JsonUtils.toJsonString(result);
    }
    
    /**
     * 
     * @param couponBathId
     * @param message
     * @return
     */
    @RequestMapping(value = "/activated", method = RequestMethod.GET)
    @Router(targetUrl = "/required-wechat")
    @WechatAuthority
    @MobileDetect
    @WechatJsConfig
    public ModelAndView activatedCoupon(@PathVariable("couponBatchId") Long couponBathId, @RequestParam("message") String message) {
        ModelAndView modelAndView = new ModelAndView("experience/coupon-activated");
        
        modelAndView.addObject("message", message);
        modelAndView.addObject("couponBatchId", couponBathId);
        
        return modelAndView;
    }
    
    /**
     * 
     * @param user
     * @param couponBatchId
     * @return
     */
    @RequestMapping(value = "/course-view", method = RequestMethod.GET)
    @Router(targetUrl = "/required-wechat")
    @WechatAuthority
    @MobileDetect
    @WechatJsConfig
    public String courseView(@Secure User user, @PathVariable("couponBatchId") Long couponBatchId) {
        
        CouponBatch couponBatch = couponService.loadCouponBatch(couponBatchId);
        
        Coupon coupon = couponService.loadCoupon(user.getId(), couponBatch);
        
        Order order = orderService.loadOrder(coupon.getId());
        
        CourseRound courseRound = courseRoundService.loadCourseRound(order);
        
        return "redirect:/profile/courses/" + courseRound.getId();
        
    }
    
}
